package com.bodu.system.template.filetemplate;

import com.bodu.system.entity.po.CodeGenConfigPo;
import com.bodu.system.entity.po.CodeGenPo;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * 模板
 *
 * @author Administrator
 */
public abstract class AbstractTemplate implements CommonTemplate {

    private final static String FILE_PREFIX = ".template.ftl";
    private final static String DEFAULT_ENCODING = "UTF-8";
    private final static String DEFAULT_BASE_PACKAGE_PATH = "/template";

    public Configuration configuration() {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setTemplateLoader(new ClassTemplateLoader(TemplateFactory.class, DEFAULT_BASE_PACKAGE_PATH));
        cfg.setDefaultEncoding(DEFAULT_ENCODING);
        return cfg;
    }

    @Override
    public void createTemplate(CodeGenPo codeGenPo, CodeGenConfigPo configPo) throws IOException, TemplateException {
        Template template = configuration().getTemplate(getTemplateName());
        String filePath = getFilePath(configPo);
        generate(template, codeGenPo, filePath);
    }

    private void generate(Template template, CodeGenPo codeGenPo, String path) throws IOException, TemplateException {
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String fileName = getFileName(path, codeGenPo, template);
        FileOutputStream fos = new FileOutputStream(fileName);
        OutputStreamWriter out = new OutputStreamWriter(fos);
        template.process(codeGenPo, out);
        fos.close();
        out.close();
    }

    private String getFileName(String path, CodeGenPo codeGenPo, Template template) {
        return path + "/" + codeGenPo.getEntityName() + template.getName().replace(FILE_PREFIX, "");
    }
}
